# 安装库: pip install business-rules
from business_rules import run_all
from business_rules.actions import rule_action
from business_rules.variables import BaseVariables, rule_variable

# 兼容性处理：获取字段类型的正确方式
try:
    # 新版本 (>=1.0) 使用 FIELD_ 前缀
    from business_rules import fields

    FIELD_NUMERIC = fields.FIELD_NUMERIC
    FIELD_TEXT = fields.FIELD_TEXT
except (ImportError, AttributeError):
    # 旧版本 (<1.0) 使用无前缀
    try:
        from business_rules.fields import NUMERIC as FIELD_NUMERIC
        from business_rules.fields import TEXT as FIELD_TEXT
        from business_rules.fields import BOOLEAN as FIELD_BOOLEAN
    except ImportError:
        # 终极回退：直接使用字符串
        FIELD_NUMERIC = "numeric"
        FIELD_TEXT = "string"
        FIELD_BOOLEAN = "boolean"


class UserVariables(BaseVariables):
    def __init__(self, user):
        self.user = user

    @rule_variable(field_type="string")
    def name(self):
        return self.user['name']


class UserActions:
    @rule_action
    def log_minor(self):
        print("⚠️ 用户未成年！")

    @rule_action
    def log_adult(self):
        print("✅ 成年用户")

    @rule_action
    def greet_vip(self):
        print(f"🎉 欢迎VIP用户 {self.user['name']}！")


# 规则配置
rules = [
    {
        "conditions": {
            "all": [{"name": "age", "operator": "<", "value": 18}]
        },
        "actions": [{"name": "log_minor"}]
    },
    {
        "conditions": {
            "all": [{"name": "age", "operator": ">=", "value": 18}]
        },
        "actions": [{"name": "log_adult"}]
    },
    {
        "conditions": {
            "all": [{"name": "is_vip", "operator": "==", "value": True}]
        },
        "actions": [{"name": "greet_vip"}]
    }
]


# 测试用户
def test_user(user):
    print(f"\n测试用户: {user['name']} ({user['age']}岁)")
    run_all(
        rule_list=rules,
        defined_variables=UserVariables(user),
        defined_actions=UserActions()
    )


# 测试案例
test_user({'name': '小明', 'age': 16})  # 未成年
test_user({'name': '小红', 'age': 25})  # 成年
test_user({'name': 'VIP用户', 'age': 30, 'vip': True})  # VIP用户